<template>
  <div v-loading="isLoading" class="app-container">
    <el-form
      ref="courseRef"
      :model="temp"
      :rules="rules"
      label-position="right"
      label-width="80px"
      size="medium"
      hide-required-asterisk
      @submit.native.prevent
    >
      <!--课程详情描述-->
      <el-card class="box-card" header="课程详情" shadow="hover">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="课程名" prop="name">
              <el-input v-model="temp.name" type="text" placeholder="课程名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="售价" prop="price">
              <el-input v-model="temp.price" type="text" placeholder="售价" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="课程容量" prop="capacity">
              <el-input v-model.number="temp.capacity" type="text" placeholder="课程容量" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="课程分类" prop="classify">
              <el-select v-model="temp.classify" placeholder="请选择分类" allow-create filterable default-first-option>
                <el-option
                  v-for="item in classList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年龄段" prop="age">
              <el-select v-model="temp.age" placeholder="请选择年龄段" allow-create filterable default-first-option>
                <el-option
                  v-for="item in ageList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任课教师" prop="teacherList">
              <el-select v-model="temp.teacherList" multiple placeholder="请选择教师" allow-create filterable default-first-option>
                <el-option
                  v-for="item in teacherList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="开课日期" prop="startEndTime">
              <el-date-picker
                v-model="temp.startEndTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开课日期"
                end-placeholder="结课日期"
                value-format="timestamp"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="课时数" prop="lessonDuration">
              <el-input v-model.number="temp.lessonDuration" type="text" placeholder="课时数" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="体验时间" prop="experienceTime">
              <el-date-picker
                v-model="temp.experienceTime"
                type="date"
                placeholder="选择体验日期"
                value-format="timestamp"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!--课程上课时间-->
      <el-card class="box-card" header="课时信息" shadow="hover">
        <el-form-item
          v-for="(domain, index) in temp.classTime"
          :key="index"
          label-width="100px"
          :label="'课时信息-' + (index+1)"
        >
          <el-input
            v-model="domain.title"
            type="text"
            placeholder="课时主题"
            style="margin: 0 10px;"
            clearable
          />
          <!--'domain.' + index + '.value'-->
          <el-date-picker
            v-model="domain.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="上课时间"
            end-placeholder="下课时间"
            value-format="timestamp"
          />
          <el-input
            v-model="domain.place"
            type="text"
            placeholder="上课地点"
            style="margin: 0 10px;"
            clearable
          />
          <el-button @click.prevent="removeDomain(domain)">删除</el-button>
        </el-form-item>
        <el-button type="primary" @click="addDomain">新增</el-button>
      </el-card>

    </el-form>

    <!--课程轮播图列表-->
    <el-card class="box-card" header="课程轮播图" shadow="hover">
      <!--上传组件-->
      <el-upload
        ref="rotation"
        action="#"
        list-type="picture-card"
        accept="image/jpeg,image/png,image/gif"
        multiple
        :file-list="temp.rotationList"
        :http-request="handleRotation"
      >
        <!--文件预览插槽-->
        <i slot="default" class="el-icon-plus" />
        <div slot="file" slot-scope="{file}">
          <img
            class="el-upload-list__item-thumbnail"
            :src="file.url"
            alt=""
          >
          <!--操作图标-->
          <span class="el-upload-list__item-actions">
            <!--预览-->
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
            >
              <i class="el-icon-zoom-in" />
            </span>
            <!--删除-->
            <span
              class="el-upload-list__item-delete"
              @click="handleRemove(file, 'rotation')"
            >
              <i class="el-icon-delete" />
            </span>
          </span>
        </div>
      </el-upload>
    </el-card>

    <!--课程详情页图片-->
    <el-card class="box-card" header="课程详情" shadow="hover">
      <mavon-editor
        ref="describe"
        v-model="courseDescribe"
        :ishljs="false"
        :autofocus="false"
        @change="handleChange"
        @imgAdd="handleUploadImage"
        @imgDel="handleDel"
      />
    </el-card>

    <el-row type="flex" justify="end">
      <el-button @click="$router.push('/course/list')">返回课程列表</el-button>
      <!--更新课程按钮-->
      <el-button type="primary" @click="updateCourse">更新课程</el-button>
    </el-row>

    <!--预览对话框-->
    <el-dialog :visible.sync="preview.dialogVisible">
      <img width="100%" :src="preview.dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import defaultSetting from '@/settings'
import { uploadFile } from '@/api/file'
import { getTeacherList } from '@/api/teacher'
import { getCourseById, getCourseAge, getCourseType, updateCourse } from '@/api/course'

// 默认表单数据
const defaultData = {
  id: undefined,
  name: '', // 课程名
  price: '', // 课程价格
  age: '', // 课程年龄段
  classify: '', // 课程分类
  teacherList: [], // 课程教师列表
  startTime: '', // 开课时间
  finishTime: '', // 结课时间
  lessonDuration: undefined, // 课时数
  capacity: undefined, // 课程容量
  experienceTime: '', // 体验时间
  classTime: [], // 上课时间
  rotationList: [], // 轮播图
  remark: '', // 课程详情
  startEndTime: [], // 开课结课日期
  state: 0
}

export default {
  name: 'UpdateCourse',
  components: { mavonEditor },
  data() {
    return {
      // 表单数据
      temp: Object.assign({}, defaultData),
      // 表单规则
      rules: {
        name: [
          {
            required: true,
            message: '请输入课程名',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入课程价格',
            trigger: 'blur'
          },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '价格格式不正确',
            trigger: 'blur'
          }
        ],
        capacity: [
          {
            required: true,
            message: '请输入课程容量',
            trigger: 'blur'
          },
          {
            type: 'number',
            message: '课程容量格式不正确',
            trigger: 'blur'
          }
        ],
        classify: [
          {
            required: true,
            message: '请选择课程分类',
            trigger: 'blur'
          }
        ],
        age: [
          {
            required: true,
            message: '请选择年龄段',
            trigger: 'blur'
          }
        ],
        teacherList: [
          {
            required: true,
            message: '请选择教师',
            trigger: 'blur'
          }
        ],
        startEndTime: [
          {
            required: true,
            message: '请选择课程开始结束时间',
            trigger: 'blur'
          }
        ],
        lessonDuration: [
          {
            type: 'number',
            message: '课时数格式不正确',
            trigger: 'blur'
          }
        ]
      },
      // 分类列表
      classList: ['音乐', '美术'],
      // 年龄段列表
      ageList: ['6-8岁', '7-10岁'],
      // 教师列表
      teacherList: [
        {
          id: 11,
          realName: '教师'
        }
      ],
      // 图片预览对象数据
      preview: {
        // 预览对话框图片路径
        dialogImageUrl: '',
        // 预览对话框可见性
        dialogVisible: false
      },
      // 课程详情 markdown 数据绑定
      courseDescribe: '',
      defaultSetting,
      isLoading: true
    }
  },
  created() {
    this.getCourseInfoById(this.$route.query.id)
    this.getTeacherList()
    this.getClassTypeList()
    this.getAgeList()
  },
  methods: {
    // 重构课程信息
    reconstructData(data) {
      this.courseDescribe = data.remark
      const teacher = []
      data.teacherList.forEach(item => {
        teacher.push(item.id)
      })
      data.teacherList = teacher
      const startEndTime = []
      startEndTime.push(data.startTime + '000')
      startEndTime.push(data.finishTime + '000')
      data.startEndTime = startEndTime
      data.experienceTime += '000'
      data.classTime.forEach(item => {
        item.value = [
          item.startTime + '000',
          item.endTime + '000'
        ]
      })
      data.rotationList.forEach(item => {
        item.url = defaultSetting.fileUrl + item.url + '/' + item.code
      })
      return data
    },
    // 获取编辑课程信息
    getCourseInfoById(id) {
      getCourseById(id).then(res => {
        this.temp = this.reconstructData(res.data)
        this.isLoading = false
      })
      // this.temp = Object.assign({}, this.$store.getters.course)
      // this.courseDescribe = this.temp.remark
      // this.$store.commit('course/SET_COURSE', {})
    },
    // 获取教师列表
    getTeacherList() {
      getTeacherList().then(res => {
        this.teacherList = res.data
      })
    },
    // 获取课程分类
    getClassTypeList() {
      getCourseType().then(res => {
        this.classList = res.data
      })
    },
    // 获取课程适合年龄段
    getAgeList() {
      getCourseAge().then(res => {
        this.ageList = res.data
      })
    },
    // 删除上课时间
    removeDomain(item) {
      const index = this.temp.classTime.indexOf(item)
      if (index !== -1) {
        this.temp.classTime.splice(index, 1)
      }
    },
    // 添加上课时间
    addDomain() {
      this.temp.classTime.push({
        value: '',
        place: '',
        title: '',
        id: Date.now()
      })
    },
    // 轮播图预览图片处理
    handlePictureCardPreview(file) {
      this.preview.dialogImageUrl = file.url
      this.preview.dialogVisible = true
    },
    // 图片删除
    handleRemove(file) {
      this.temp.rotationList = this.temp.rotationList.filter(item => item.uid !== file.uid)
    },
    // 轮播图上传
    handleRotation(request) {
      // 获取上传文件
      const formData = new FormData()
      formData.append('file', request.file)
      // 请求后台
      uploadFile(formData).then((res) => {
        const file = {
          id: res.data.id,
          name: request.file.name,
          url: process.env.VUE_APP_REAL_API + '/static/' + res.data.url
        }
        // 将文件放入已上传列表
        this.temp.rotationList.push(file)
        this.$notify({
          title: '成功',
          message: '文件上传成功',
          type: 'success',
          duration: 2000
        })
      }).catch(() => {
        // 上传失败
      })
    },
    // 课程描述图片上传处理
    handleUploadImage(pos, file) {
      // 第一步.封装文件数据
      const formData = new FormData()
      formData.append('file', file)

      // 上传文件
      uploadFile(formData).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        this.$refs.describe.$img2Url(pos, defaultSetting.fileUrl + res.data.url)
      })
    },
    // 课程描述图片删除处理
    handleDel(filename) {
      console.log('手动删除图片->' + filename)
    },
    // 监听markdown变化，动态绑定课程详情
    handleChange(value, render) {
      this.temp.remark = render
    },
    // 更新课程前封装数据
    buildData() {
      const data = Object.assign({}, this.temp)

      // 封装教师列表
      if (data.teacherList.length !== 0) {
        const teacherList = []
        data.teacherList.forEach(item => {
          console.log(item)
          const t = {
            id: item
          }
          teacherList.push(t)
        })
        data.teacherList = teacherList
      }

      // 封装上课时间
      if (data.classTime.length !== 0) {
        const classTime = []
        data.classTime.forEach(item => {
          const c = {
            startTime: Number.parseInt(item.value[0].toString().substring(0, 10)),
            endTime: Number.parseInt(item.value[1].toString().substring(0, 10)),
            place: item.place,
            title: item.title
          }
          classTime.push(c)
        })
        data.classTime = classTime
      }

      // 封装时间数据
      if (data.startEndTime !== []) {
        data.startTime = Number.parseInt(data.startEndTime[0].toString().substring(0, 10))
        data.finishTime = Number.parseInt(data.startEndTime[1].toString().substring(0, 10))
      }

      // 封装体验时间
      if (data.experienceTime !== '') {
        data.experienceTime = Number.parseInt(data.experienceTime.toString().substring(0, 10))
      }

      return data
    },
    // 更新课程
    updateCourse() {
      // 表单校验
      this.$refs.courseRef.validate(valid => {
        if (valid) {
          this.isLoading = true
          // 更新课程
          updateCourse(JSON.stringify(this.buildData())).then(res => {
            this.$notify.success({
              title: '成功',
              message: res.msg,
              duration: 2000
            })
            // 清空数据
            this.temp = Object.assign({}, defaultData)
            this.temp.rotationList = []
            this.temp.classTime = []
            this.courseDescribe = ''
            this.isLoading = false
            this.$router.push('/course/list')
          }).catch(() => {
            this.isLoading = false
          })
        }
      })
    }
  }
}
</script>

<!--suppress CssUnusedSymbol -->
<style scoped>
.el-input {
  width: 205px;
}
.el-card {
  margin: 20px 0;
}
</style>
